<template>
  <div class="order-detail-page">
    <!-- 页面头部 -->
    <van-nav-bar 
      title="订单详情" 
      left-arrow 
      @click-left="goBack" 
    />
    
    <!-- 订单状态 -->
    <div class="status-section">
      <div class="status-card">
        <div class="status-icon">
          <van-icon :name="getStatusIcon(orderDetail.status)" size="24" />
        </div>
        <div class="status-info">
          <div class="status-text">{{ getStatusText(orderDetail.status) }}</div>
          <div class="status-desc">{{ getStatusDescription(orderDetail.status) }}</div>
        </div>
      </div>
    </div>
    
    <!-- 订单信息 -->
    <div class="order-info-section">
      <div class="section-title">订单信息</div>
      <div class="info-card">
        <div class="info-item">
          <span class="label">订单号：</span>
          <span class="value">{{ orderDetail.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单类型：</span>
          <span class="value">
            <span class="type-tag" :class="getOrderTypeClass(orderDetail.type)">
              {{ getOrderTypeText(orderDetail.type) }}
            </span>
          </span>
        </div>
        <div class="info-item">
          <span class="label">下单时间：</span>
          <span class="value">{{ formatTime(orderDetail.placedTime) }}</span>
        </div>
        <div class="info-item" v-if="orderDetail.payTime">
          <span class="label">支付时间：</span>
          <span class="value">{{ formatTime(orderDetail.payTime) }}</span>
        </div>
      </div>
    </div>
    
    <!-- 商品信息 -->
    <div class="goods-section">
      <div class="section-title">商品信息</div>
      <div class="goods-card">
        <div 
          v-for="item in orderDetail.snapItems" 
          :key="item.id" 
          class="goods-item"
        >
          <img :src="item.img" :alt="item.title" class="goods-image" />
          <div class="goods-info">
            <div class="goods-title">{{ item.title }}</div>
            <div class="goods-specs" v-if="item.specs && item.specs.length">
              <span v-for="spec in item.specs" :key="spec.key" class="spec-tag">
                {{ spec.key }}: {{ spec.value }}
              </span>
            </div>
            <div class="goods-price">
              <span class="price">¥{{ formatPrice(item.price) }}</span>
              <span class="count">x{{ item.count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 价格信息 -->
    <div class="price-section">
      <div class="section-title">价格信息</div>
      <div class="price-card">
        <div class="price-item">
          <span class="label">商品总价：</span>
          <span class="value">¥{{ formatPrice(orderDetail.totalPrice) }}</span>
        </div>
        <div class="price-item" v-if="orderDetail.finalTotalPrice !== orderDetail.totalPrice">
          <span class="label">实付金额：</span>
          <span class="value final-price">¥{{ formatPrice(orderDetail.finalTotalPrice) }}</span>
        </div>
        <div class="price-item" v-if="orderDetail.type === 'points'">
          <span class="label">使用积分：</span>
          <span class="value points-used">{{ getPointsUsed(orderDetail) }} 积分</span>
        </div>
        <div class="price-item" v-if="orderDetail.type === 'vip' && orderDetail.payAmount">
          <span class="label">支付金额：</span>
          <span class="value">¥{{ formatPrice(orderDetail.payAmount) }}</span>
        </div>
      </div>
    </div>
    
    <!-- 收货地址 -->
    <div class="address-section" v-if="orderDetail.snapAddress">
      <div class="section-title">收货地址</div>
      <div class="address-card">
        <div class="address-info">
          <van-icon name="location-o" size="16" color="#157658" />
          <div class="address-details">
            <div class="contact-info">
              <span class="name">{{ orderDetail.snapAddress.name }}</span>
              <span class="phone">{{ orderDetail.snapAddress.phone }}</span>
            </div>
            <div class="address-text">{{ orderDetail.snapAddress.address }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 二手订单特殊信息 -->
    <div class="vip-info-section" v-if="orderDetail.type === 'vip'">
      <div class="section-title">支付信息</div>
      <div class="vip-info-card">
        <!-- 支付截图 -->
        <div class="payment-proof" v-if="orderDetail.payImage">
          <div class="proof-title">支付截图</div>
          <div class="proof-image">
            <img 
              :src="orderDetail.payImage" 
              :alt="支付截图"
              @click="previewImage(orderDetail.payImage)"
              class="proof-img"
            />
          </div>
        </div>
        
        <!-- 支付状态 -->
        <div class="payment-status">
          <div class="status-item">
            <span class="label">支付状态：</span>
            <span class="value" :class="getPaymentStatusClass(orderDetail.checked)">
              {{ getPaymentStatusText(orderDetail.checked) }}
            </span>
          </div>
          
          <!-- 确认时间 -->
          <div class="status-item" v-if="orderDetail.confirmTime">
            <span class="label">确认时间：</span>
            <span class="value">{{ formatTime(orderDetail.confirmTime) }}</span>
          </div>
          
          <!-- 支付金额 -->
          <div class="status-item" v-if="orderDetail.payAmount">
            <span class="label">支付金额：</span>
            <span class="value">¥{{ formatPrice(orderDetail.payAmount) }}</span>
          </div>
        </div>
        
        <!-- 拒绝记录 -->
        <div class="rejection-records" v-if="orderDetail.rejectionRecords && orderDetail.rejectionRecords.length">
          <div class="rejection-title">拒绝记录</div>
          <div 
            v-for="record in orderDetail.rejectionRecords" 
            :key="record.id" 
            class="rejection-item"
          >
            <div class="rejection-header">
              <span class="rejection-time">{{ formatTime(record.rejectTime) }}</span>
              <span class="rejection-amount" v-if="record.receivedAmount">
                收到金额：¥{{ formatPrice(record.receivedAmount) }}
              </span>
            </div>
            <div class="rejection-reason" v-if="record.rejectReason">
              拒绝原因：{{ record.rejectReason }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="action-section">
      <van-button 
        v-if="canConfirmReceive" 
        type="primary" 
        size="large" 
        @click="confirmReceive"
        class="action-btn"
      >
        确认收货
      </van-button>
      
      <van-button 
        v-if="canPublishSecondhand" 
        type="success" 
        size="large" 
        @click="publishSecondhand"
        class="action-btn"
      >
        发布二手
      </van-button>
      
      <van-button 
        type="default" 
        size="large" 
        @click="goBack"
        class="action-btn"
      >
        返回
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showConfirmDialog, showImagePreview } from 'vant'
import { getMyPurchaseDetail } from '@/api/order'
import { confirmReceiveOrder } from '@/api/order'

const route = useRoute()
const router = useRouter()

// 响应式数据
const orderDetail = ref({})
const loading = ref(false)

// 计算属性
const canConfirmReceive = computed(() => {
  return orderDetail.value.status === 3 // 已发货状态
})

const canPublishSecondhand = computed(() => {
  const order = orderDetail.value
  // 二手订单：已确认状态可以发布
  if (order.type === 'vip' && order.checked === 1) {
    return true
  }
  // 普通订单：已完成状态可以发布
  if (order.type === 'normal' && order.status === 4) {
    return true
  }
  // 积分订单：已支付状态可以发布
  if (order.type === 'points' && order.status === 2) {
    return true
  }
  return false
})

// 获取订单详情
const loadOrderDetail = async () => {
  const orderId = route.query.id
  if (!orderId) {
    showToast('订单ID不能为空')
    return
  }
  
  loading.value = true
  try {
    const response = await getMyPurchaseDetail(orderId)
    if (response.success) {
      orderDetail.value = response.data || {}
    } else {
      showToast(response.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    showToast('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    1: 'clock-o',      // 待付款
    2: 'passed',       // 已支付
    3: 'logistics',    // 已发货
    4: 'completed',    // 已完成
    5: 'close'         // 已取消
  }
  return iconMap[status] || 'info-o'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    1: '待付款',
    2: '已支付',
    3: '已发货',
    4: '已完成',
    5: '已取消'
  }
  return textMap[status] || '未知状态'
}

// 获取状态描述
const getStatusDescription = (status) => {
  const descMap = {
    1: '请尽快完成支付',
    2: '订单已支付成功',
    3: '商品正在配送中',
    4: '订单已完成',
    5: '订单已取消'
  }
  return descMap[status] || ''
}

// 获取订单类型样式类
const getOrderTypeClass = (type) => {
  const classMap = {
    'points': 'type-points',
    'vip': 'type-vip',
    'normal': 'type-normal'
  }
  return classMap[type] || 'type-default'
}

// 获取订单类型文本
const getOrderTypeText = (type) => {
  const textMap = {
    'points': '积分订单',
    'vip': '二手订单',
    'normal': '普通订单'
  }
  return textMap[type] || '未知类型'
}

// 获取支付状态样式类
const getPaymentStatusClass = (checked) => {
  const classMap = {
    0: 'status-pending',
    1: 'status-confirmed',
    2: 'status-rejected'
  }
  return classMap[checked] || 'status-default'
}

// 获取支付状态文本
const getPaymentStatusText = (checked) => {
  const textMap = {
    0: '待确认',
    1: '已确认',
    2: '已拒绝'
  }
  return textMap[checked] || '未知状态'
}

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

// 获取使用的积分
const getPointsUsed = (order) => {
  if (order.type !== 'points') return 0
  const discount = order.totalPrice - order.finalTotalPrice
  return Math.floor(discount * 10)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 预览图片
const previewImage = (imageUrl) => {
  showImagePreview({
    images: [imageUrl],
    startPosition: 0,
    closeable: true
  })
}

// 确认收货
const confirmReceive = async () => {
  try {
    await showConfirmDialog({
      title: '确认收货',
      message: '确认已收到商品？'
    })
    
    const response = await confirmReceiveOrder(orderDetail.value.id)
    if (response.success) {
      showToast('确认收货成功')
      // 刷新订单状态
      orderDetail.value.status = 4
    } else {
      showToast(response.message || '确认收货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      showToast('确认收货失败')
    }
  }
}

// 发布二手
const publishSecondhand = async () => {
  try {
    // 计算建议价格（按购买支付金额）
    const suggestedPrice = orderDetail.value.finalTotalPrice || orderDetail.value.totalPrice
    
    // 根据订单类型显示不同的提示
    let title = '发布二手商品'
    let message = `建议价格：¥${formatPrice(suggestedPrice)}\n确认发布为二手商品？`
    
    if (orderDetail.value.type === 'vip') {
      title = '重新发布二手商品'
      message = `建议价格：¥${formatPrice(suggestedPrice)}\n确认重新发布为二手商品？`
    } else if (orderDetail.value.type === 'points') {
      title = '发布积分商品'
      message = `建议价格：¥${formatPrice(suggestedPrice)}\n确认发布为积分商品？`
    }
    
    await showConfirmDialog({
      title: title,
      message: message
    })
    
    // 跳转到二手发布页面，传递商品信息
    router.push({
      path: '/vip-order',
      query: {
        fromOrder: orderDetail.value.id,
        suggestedPrice: suggestedPrice,
        productInfo: JSON.stringify({
          title: orderDetail.value.snapTitle || '二手商品',
          image: orderDetail.value.snapImg,
          specs: orderDetail.value.snapItems
        })
      }
    })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布二手失败:', error)
      showToast('发布二手失败')
    }
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadOrderDetail()
})
</script>

<style lang="scss" scoped>
.order-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100px;
}

.status-section {
  padding: 15px;
  
  .status-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border-radius: 16px;
    padding: 24px;
    display: flex;
    align-items: center;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
    border: 1px solid #e9ecef;
    
    .status-icon {
      margin-right: 18px;
      color: #157658;
      filter: drop-shadow(0 2px 4px rgba(21, 118, 88, 0.2));
    }
    
    .status-info {
      .status-text {
        font-size: 20px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 6px;
        background: linear-gradient(135deg, #157658 0%, #0f5a3f 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }
      
      .status-desc {
        font-size: 14px;
        color: #6c757d;
        font-weight: 500;
      }
    }
  }
}

.order-info-section,
.goods-section,
.price-section,
.address-section,
.vip-info-section {
  padding: 15px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
    padding-left: 10px;
    border-left: 3px solid #157658;
  }
  
  .info-card,
  .goods-card,
  .price-card,
  .address-card,
  .vip-info-card {
    background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
    border-radius: 12px;
    padding: 18px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid #f0f2f5;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
    }
  }
}

.info-card {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      font-size: 14px;
      color: #666;
    }
    
    .value {
      font-size: 14px;
      color: #333;
      
      .type-tag {
        padding: 2px 8px;
        border-radius: 4px;
        color: #fff;
        font-size: 12px;
        
        &.type-points {
          background: #ff6b6b;
        }
        
        &.type-vip {
          background: #157658;
        }
        
        &.type-normal {
          background: #4a90e2;
        }
        
        &.type-default {
          background: #999;
        }
      }
    }
  }
}

.goods-card {
  .goods-item {
    display: flex;
    margin-bottom: 15px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .goods-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 8px;
      margin-right: 15px;
    }
    
    .goods-info {
      flex: 1;
      
      .goods-title {
        font-size: 16px;
        color: #333;
        margin-bottom: 8px;
        line-height: 1.4;
      }
      
      .goods-specs {
        margin-bottom: 8px;
        
        .spec-tag {
          display: inline-block;
          font-size: 12px;
          color: #666;
          background: #f5f5f5;
          padding: 2px 6px;
          border-radius: 4px;
          margin-right: 5px;
          margin-bottom: 5px;
        }
      }
      
      .goods-price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price {
          font-size: 16px;
          font-weight: bold;
          color: #ff6b6b;
        }
        
        .count {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }
}

.price-card {
  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      font-size: 14px;
      color: #666;
    }
    
    .value {
      font-size: 14px;
      color: #333;
      
      &.final-price {
        color: #ff6b6b;
        font-weight: bold;
      }
      
      &.points-used {
        color: #157658;
        font-weight: bold;
      }
    }
  }
}

.address-card {
  .address-info {
    display: flex;
    align-items: flex-start;
    
    .address-details {
      margin-left: 10px;
      flex: 1;
      
      .contact-info {
        margin-bottom: 8px;
        
        .name {
          font-size: 16px;
          font-weight: bold;
          color: #333;
          margin-right: 15px;
        }
        
        .phone {
          font-size: 14px;
          color: #666;
        }
      }
      
      .address-text {
        font-size: 14px;
        color: #333;
        line-height: 1.4;
      }
    }
  }
}

.vip-info-card {
  .payment-proof {
    margin-bottom: 20px;
    
    .proof-title {
      font-size: 14px;
      color: #333;
      margin-bottom: 10px;
      font-weight: bold;
    }
    
    .proof-image {
      .proof-img {
        width: 200px;
        height: 200px;
        object-fit: contain;
        border: 1px solid #eee;
        border-radius: 8px;
        cursor: pointer;
        
        &:hover {
          border-color: #157658;
        }
      }
    }
  }
  
  .payment-status {
    margin-bottom: 20px;
    
    .status-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        font-size: 14px;
        color: #666;
      }
      
      .value {
        font-size: 14px;
        color: #333;
        
        &.status-pending {
          color: #ff976a;
        }
        
        &.status-confirmed {
          color: #07c160;
        }
        
        &.status-rejected {
          color: #ff6b6b;
        }
        
        &.status-default {
          color: #999;
        }
      }
    }
  }
  
  .rejection-records {
    .rejection-title {
      font-size: 14px;
      color: #333;
      margin-bottom: 10px;
      font-weight: bold;
    }
    
    .rejection-item {
      background: #f8f8f8;
      border-radius: 6px;
      padding: 12px;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .rejection-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        .rejection-time {
          font-size: 12px;
          color: #666;
        }
        
        .rejection-amount {
          font-size: 12px;
          color: #ff6b6b;
          font-weight: bold;
        }
      }
      
      .rejection-reason {
        font-size: 12px;
        color: #333;
        line-height: 1.4;
      }
    }
  }
}

.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  padding: 18px 15px;
  border-top: 1px solid #e9ecef;
  display: flex;
  gap: 15px;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08);
  
  .action-btn {
    flex: 1;
    height: 48px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 16px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-1px);
    }
    
    &.van-button--primary {
      background: linear-gradient(135deg, #157658 0%, #0f5a3f 100%);
      border: none;
      box-shadow: 0 4px 16px rgba(21, 118, 88, 0.3);
    }
    
    &.van-button--success {
      background: linear-gradient(135deg, #07c160 0%, #06ad56 100%);
      border: none;
      box-shadow: 0 4px 16px rgba(7, 193, 96, 0.3);
    }
  }
}
</style> 